<div id="packagingOverview" style="height:100%">
    <div class="ui-layout-west" id="tableAndTF">
        <div id="packagingOverviewTable_holder" class="ui-layout-center">
            <div class="clearfix tbl packagingOverviewTable" id="packagingOverviewTable"></div>
        </div>
        <div id="timeFilter_holder" class="clearfix ui-layout-south"></div>        
    </div>
    <div class="ui-layout-center">
        <div id="packagingOverviewForm_holder" class="full-height"></div>    
    </div>
</div>
<script>
    var PackagingOverviewFX = function() {
        var _self = this;
        _self.LOCKS = {
            packagingOverviewForm: false
        };
        _self.perform = function() {
            //dodavanje layout-a za parent div
            $("#packagingOverview").layout({
                resizable: false,
                closable: false,
                west__size: "630"
            });
            //ucitavanje forme i dodavanje layouta za njen content
            $("#packagingOverviewForm_holder").load("_parts/2_Packaging/OverviewForm.html?x=" + Math.random(), function() {
                $("#packagingOverviewForm").layout({
                    resizable: false,
                    closable: false,
                    west__size: "100"
                });
            });
            //ucitavanje time filtera
            $("#timeFilter_holder").load("_parts/TimeFilter.html?x=" + Math.random(), function() {
                $('.datepicker.hook_dateFrom').datepicker({
                    defaultDate: '-3m',
                    dateFormat: 'd.m.yy'
                }).datepicker('setDate', '-3m');
                $('.datepicker.hook_dateTo').datepicker({
                    defaultDate: new Date(),
                    dateFormat: 'd.m.yy'
                }).datepicker('setDate', new Date());

                _self.loadYearsForTimeFilter();
                _self.loadLinesForTimeFilter();

                //$(".timeFilter #row1 .col5").remove();
                $(".timeFilter #row2 .col5").remove();
                $(".timeFilter #row3 .col5").remove();
                //$(".timeFilter #row4 .col4").remove();

                $("#tableAndTF").layout({
                    resizable: false,
                    closable: false,
                    south__size: "120"
                });
                $("#packagingOverviewTable").addScroll();
                _self.loadDataForPackagingTable();
            });

            window.refreshAndSortTable = _self.refreshSortedTable;
        };
        _self.refreshSortedTable = function(table, columnName, ascDesc, callback){
            _self.table = table;
            _self.request = 200;

            _self.columnName = columnName;
            _self.sortItem = "";
            _self.ascDesc = ascDesc;
            _self.action = "getItems";

            _self.random = Math.random();
            _self.url = "js/tableParams/" + _self.request + ".json?x=" + random;

            $.get(_self.url, function(response) {
                $(response.desc).each(function(index,value){
                    if(value.title == columnName){
                        _self.sortItem = value.param;
                        return false;
                    }
                });

                var params = {
                    request: _self.request,
                    action: _self.action,
                    sortItem: _self.sortItem,
                    ascDesc: _self.ascDesc
                };

                window.tableConstructor.generateTable(params, callback);
            });

        };

        _self.refresh = function() {
            $("body").css('cursor', 'wait');
            _self.loadDataForPackagingTable(function() {
                $("body").css('cursor', 'default');
            });
        };
        _self.exportCSV = function() {
            var params = _self.getTimeFilterParams();
            params.request = 200;
            params.dataType = "csv";
            var url = createURL(window.CONSTANTS.SERVICE_URL_DIRECT, "?", params);
            window.open(url, "Export CSV", "height=200, width=300, top=50, left=200");
        };
        _self.getTimeFilterParams = function() {
            var params = {};
            var type = $(".timeFilter .radio:checked").data('type');

            if (parseInt($('.timeFilter .hook_line').val()) > 0) {
                params.line = $('.timeFilter .hook_line').val();
            }

            switch (type) {
                case 'period':
                    params.pStart = $('.timeFilter .hook_dateFrom').val();
                    if ($('.timeFilter .hook_oneDay').is(":checked")) {
                        params.pOneDay = 'oneDay';
                    } else {
                        params.pEnd = $('.timeFilter .hook_dateTo').val();
                    }
                    params.timeFrame = 'period';
                    break;
                case 'month':
                    params.mMonth = $('.timeFilter .hook_mMonth').val();
                    params.mYear = $('.timeFilter .hook_mYear').val();
                    params.timeFrame = 'month';
                    break;
                case 'year':
                    params.yYear = $('.timeFilter .hook_yYear').val();
                    params.timeFrame = 'year';
                    break;
            }
            return params;
        };
        _self.updateForm = function(id) {
            if (!_self.LOCKS.packagingOverviewForm) {
                _self.LOCKS.packagingOverviewForm = true;
                _self.loadDataForPackagingForm(id, function() {
                    _self.LOCKS.packagingOverviewForm = false;
                });
            }
        };

        _self.loadDataForPackagingTable = function(callback) {
            var params = {
                request: 200,
                action: "getItems"
            };
            window.tableConstructor.generateTable(params, callback);
        };
        _self.loadDataForPackagingForm = function(id, callback) {
            var params = {
                request: 202,
                action: 'getItems',
                id: id
            };
            $.getJSON(window.CONSTANTS.SERVICE_URL, params, function(response) {
                $("#202_productionOrder").val(response[0].productionOrder);
                $("#202_shift").val(response[0].shift);
                $("#202_PE").val(response[0].PE);
                $("#202_recipe").html("<option>" + response[0].recipeNo + "</option>");
                $("#202_minutes").val(response[0].minutes);
                $("#202_description").val(response[0].description);
                $("#202_startTime").val(response[0].startTime);
                $("#202_endTime").val(response[0].endTime);
                $("#202_speed").val(response[0].speed);
                $("#202_actualSpeed").val(response[0].actualSpeed);
                $("#202_line").html("<option>" + response[0].line + "</option>");
                $("#202_notes").val(response[0].notes);
                $("#202_modifiedBy").val(response[0].modifiedBy);
                $("#202_modifiedDate").val(response[0].modifiedDate);
                $("#202_user").html("<option>" + response[0].userName + "</option>");
                $("#202_attendants").val(response[0].attendant);
                $("#202_packers").val(response[0].packers);
                $("#202_rollCodeBin").val(response[0].rollCodeBin);
                $("#202_fillingMachine").val(response[0].fillingMachine);
                $("#202_noMixNoMaterial").val(response[0].noMixNoMaterial);
                $("#202_cartonerWrapper").val(response[0].cartonerWrapper);
                $("#202_uncounted").val(response[0].unaccounted);
                $("#202_checkWeigher").val(response[0].weighter);
                $("#202_changeover").val(response[0].changeOver);
                $("#202_casepacker").val(response[0].casePacker);
                $("#202_pouches").val(response[0].pouches);
                $("#202_pouchesTotal").val(response[0].pouchesTotal);
                $("#202_cases").val(response[0].cases);
                $("#202_casesTotal").val(response[0].casesTotal);
                $("#202_web").val(response[0].web);
                $("#202_webTotal").val(response[0].webTotal);
                $("#202_powder").val(response[0].powder);
                $("#202_powderTotal").val(response[0].powderTotal);
                $("#202_alarmsDuration").val(response[0].alm_sum);
                if (callback) {
                    callback();
                }
            });
        };
        _self.loadYearsForTimeFilter = function(callback) {
            $.getJSON(window.CONSTANTS.SERVICE_URL, {
                request: 200,
                action: 'getYears'
            },
            function(response) {
                $.each(response, function(index, value) {
                    $(".timeFilter .hook_yYear").append("<option>" + value.availableYear + "</option>");
                    $(".timeFilter .hook_mYear").append("<option>" + value.availableYear + "</option>");
                });
                if (callback) {
                    callback();
                }
            });
        };
        _self.loadLinesForTimeFilter = function(callback) {
            $.getJSON(window.CONSTANTS.SERVICE_URL, {
                request: 200,
                action: 'getLines'
            },
            function(response) {
                $(".timeFilter .hook_line").html("").append("<option selected value='0'>All</option>");
                $.each(response, function(index, value) {
                    $(".timeFilter .hook_line").append("<option value=" + value.availableLine + ">" + value.availableLine + "</option>");
                });
                if (callback) {
                    callback();
                }
            });
        };
        _self.loadRecipesForSelect = function(){
            alert("recipes");
        };
        _self.loadLinesForSelect = function(){
            alert("lines");
        };
        _self.loadUsersForSelect = function(){
            alert("users");
        };
        _self.assignEventHandlers = function() {
            $(document).on("click", ".timeFilter button.refresh", function() {
                _self.refresh();
            });
            $(document).on("click", ".timeFilter button.export", function() {
                _self.exportCSV();
            });
            $(document).on("click", "#202_material", function() {
                _self.openMaterialTable();
            });
            $(document).on("click", "#202_recipe", function() {
                _self.loadRecipesForSelect();
            });
            $(document).on("click", "#202_line", function() {
                _self.loadLinesForSelect();
            });
            $(document).on("click", "#202_user", function() {
                _self.loadUsersForSelect();
            });
            $(document).on("click", "#packagingOverviewTable_holder .scrollable .row.data", function() {
                $("#packagingOverviewTable_holder .scrollable .row.data").removeClass("selected");
                $(this).addClass("selected");
                var id = $(this).data("id");
                _self.updateForm(id);
            });
        };
        _self.clearEventHandlers = function() {
            $(document).off("click", ".timeFilter button.refresh");
            $(document).off("click", ".timeFilter button.export");
            $(document).off("click", "#202_material");
            $(document).off("click", "#202_recipe");
            $(document).off("click", "#202_line");
            $(document).off("click", "#202_user");
            $(document).off("click", "#packagingOverviewTable_holder .scrollable .row.data");
        };
        _self.openMaterialTable = function() {
            var state = 25;
            window.materialID = $("#202_recipe").val();

            updateURL(state);
        };
        _self.loadDataForMaterialTable = function(callback) {
            var params = {
                request: 250,
                action: "getItems"
            };
            window.tableConstructor.generateTable(params, callback);
        };
    };
    if (!window.pOverviewFX) {
        window.pOverviewFX = new PackagingOverviewFX();
        window.pOverviewFX.clearEventHandlers();
        window.pOverviewFX.assignEventHandlers();
        window.pOverviewFX.perform();
    }
    else {
        window.pOverviewFX.clearEventHandlers();
        window.pOverviewFX.assignEventHandlers();
        window.pOverviewFX.perform();
    }
</script>